package com.eastfair.imaster.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.auth.entity.UserAccount;
import com.eastfair.auth.entity.UserOrganization;
import com.eastfair.auth.vo.UserOrganizationVo;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.common.ResourceCacheKeyBuilder;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.imaster.dao.BusinResourceMapper;
import com.eastfair.imaster.dto.BusinResourceDTO;
import com.eastfair.imaster.dto.ResourceOfFile;
import com.eastfair.imaster.dto.ResourceOfNew;
import com.eastfair.imaster.dto.ResourceOfVideo;
import com.eastfair.imaster.entity.BusinResource;
import com.eastfair.imaster.enumeration.BusinResourceResourceTypeEnum;
import com.eastfair.imaster.enumeration.BusinResourceStatusEnum;
import com.eastfair.imaster.service.BusinResourceService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.imaster.vo.BusinResourceVO;
import com.eastfair.notice.vo.CommentVO;
import com.eastfair.projectcore.entity.Menu;
import com.eastfair.uid.model.SelfUidDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 业务资源表
 * </p>
 *
 * @author ligang
 * @date 2022-01-20
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class BusinResourceServiceImpl extends SuperCacheServiceImpl<BusinResourceMapper, BusinResource> implements BusinResourceService {
//    @Autowired
//    SelfUidService selfUidService;

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(BusinResource model) {
        //雪花ID,不需要分库分表
        SelfUidDto selfUidDto = new SelfUidDto();
//        model.setId(selfUidService.getUid(selfUidDto));
        model.setId(DefaultUidGenerator.getUid(0L));
        if (model.getSequence() == null) {
            //排序
            model.setSequence(1);
            if (model.getCorrelationId() != null) {
                model.setSequence(querySort(model));
            }
        }
        return R.successDef();
    }

    public int querySort(BusinResource businResource) {
        QueryWrapper<BusinResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BusinResource::getCorrelationId, businResource.getCorrelationId());
        queryWrapper.lambda().eq(BusinResource::getResourceType, businResource.getResourceType());
        queryWrapper.lambda().eq(BusinResource::getIsDeleted, BusinessConstant.DELETE_NO);
        //排序查询
        queryWrapper.orderByAsc("sequence");
        List<BusinResource> businResourceList = list(queryWrapper);
        if (businResourceList != null && !businResourceList.isEmpty()) {
            int max = businResourceList.stream().mapToInt(s -> s.getSequence()).max().getAsInt();
            return max + 1;
        }
        return 1;
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<BusinResource> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new ResourceCacheKeyBuilder();
    }

    @Override
    public BusinResourceVO executeSave(BusinResourceDTO businResourceDTO) {
        BusinResource businResource = new BusinResource();
        BeanUtils.copyProperties(businResourceDTO, businResource);
        if (businResourceDTO.getResourceType() != null) {
            if (BusinResourceResourceTypeEnum.NEWS.getCode().equals(businResourceDTO.getResourceType().getCode())) {
                //新闻
                businResource.setBusinDetails(JSON.toJSONString(businResourceDTO.getResourceOfNew()));
            } else if (BusinResourceResourceTypeEnum.DATA.getCode().equals(businResourceDTO.getResourceType().getCode())) {
                //资料
                businResource.setBusinDetails(JSON.toJSONString(businResourceDTO.getResourceOfFileList()));
                businResource.setTitle(businResourceDTO.getResourceOfFileList().get(0).getDataName());
            } else if (BusinResourceResourceTypeEnum.VIDEO.getCode().equals(businResourceDTO.getResourceType().getCode())) {
                //视频
                String advertsVideo = businResourceDTO.getAdvertsVideo();
                String advertsVideoImage = businResourceDTO.getAdvertsVideoImage();
                if (StringUtils.isNotBlank(advertsVideo) && StringUtils.isNotBlank(advertsVideoImage)) {
                    List<String> advertsVideoList = JSONArray.parseArray(advertsVideo, String.class);
                    List<String> advertsVideoImageList = JSONArray.parseArray(advertsVideoImage, String.class);
                    List<ResourceOfVideo> resourceOfVideoList = new ArrayList<>();
                    if (advertsVideoList != null && !advertsVideoList.isEmpty()) {
                        for (int i = 0; i < advertsVideoList.size(); i++) {
                            ResourceOfVideo resourceOfVideo = new ResourceOfVideo();
                            resourceOfVideo.setHeadImg(advertsVideoImageList.get(i));
                            resourceOfVideo.setDataUrl(advertsVideoList.get(i));
                            resourceOfVideo.setVideoText(businResourceDTO.getVideoText());
                            resourceOfVideoList.add(resourceOfVideo);
                        }
                    }
                    businResource.setBusinDetails(JSON.toJSONString(resourceOfVideoList));
                }

            }
        }
        if (businResourceDTO.getId() == null) {
            if (businResourceDTO.getStatus() == null) {
                //默认待审核状态
                businResource.setStatus(BusinResourceStatusEnum.WAITING);
            }
            businResource.setIsEnable(BusinessConstant.YES);
            businResource.setIsDeleted(BusinessConstant.NO);
            businResource.setIsShelves(BusinessConstant.NO);
            save(businResource);
        } else {
            //修改
            updateById(businResource);
        }
        return doToVo(businResource);
    }

    @Override
    public BusinResourceVO executeUpdate(BusinResourceDTO businResourceDTO) {
        BusinResource businResource = new BusinResource();
        BeanUtils.copyProperties(businResourceDTO, businResource);
        if (businResourceDTO.getResourceType() != null && BusinResourceResourceTypeEnum.NEWS.getCode().equals(businResourceDTO.getResourceType().getCode())) {
            //新闻
            businResource.setBusinDetails(JSON.toJSONString(businResourceDTO.getResourceOfNew()));
        }
        if (businResourceDTO.getStatus() == null) {
            //默认待审核状态
            businResource.setStatus(BusinResourceStatusEnum.WAITING);
        }
        businResource.setIsEnable(BusinessConstant.YES);
        businResource.setIsDeleted(BusinessConstant.NO);
        updateById(businResource);
        return doToVo(businResource);
    }

    @Override
    public void assembleBusinResourceList(List<BusinResourceVO> businResourceVOList) {
        if (businResourceVOList == null || businResourceVOList.isEmpty()) {
            return;
        }
        for (BusinResourceVO businResourceVO : businResourceVOList) {
            businResourceVO.getBusinDetails();
            if (businResourceVO.getResourceType() != null && BusinResourceResourceTypeEnum.NEWS.getCode().equals(businResourceVO.getResourceType().getCode())) {
                //新闻
                businResourceVO.setResourceOfNew(JSONObject.parseObject(businResourceVO.getBusinDetails(), ResourceOfNew.class));
            } else if (businResourceVO.getResourceType() != null && BusinResourceResourceTypeEnum.DATA.getCode().equals(businResourceVO.getResourceType().getCode())) {
                //资料
                businResourceVO.setResourceOfFileList(JSONArray.parseArray(businResourceVO.getBusinDetails(), ResourceOfFile.class));
            } else if (businResourceVO.getResourceType() != null && BusinResourceResourceTypeEnum.VIDEO.getCode().equals(businResourceVO.getResourceType().getCode())) {
                //视频
                List<ResourceOfVideo> resourceOfVideoList = JSONArray.parseArray(businResourceVO.getBusinDetails(), ResourceOfVideo.class);
//                businResourceVO.setResourceOfVideoList(JSONArray.parseArray(businResourceVO.getBusinDetails(), ResourceOfVideo.class));
                //视频
                List<String> advertsVideoList = new ArrayList<>();
                List<String> advertsVideoImage = new ArrayList<>();
                if (resourceOfVideoList != null && !resourceOfVideoList.isEmpty()) {
                    for (ResourceOfVideo resourceOfVideo : resourceOfVideoList) {
                        advertsVideoImage.add(resourceOfVideo.getHeadImg());
                        advertsVideoList.add(resourceOfVideo.getDataUrl());
                    }
                    businResourceVO.setVideoText(resourceOfVideoList.get(0).getVideoText());
                }
                businResourceVO.setAdvertsVideo(JSON.toJSONString(advertsVideoList));
                businResourceVO.setAdvertsVideoImage(JSON.toJSONString(advertsVideoImage));

            }
        }
    }

    @Override
    public BusinResourceVO findById(Long id) {
        BusinResource businResource = getById(id);
        return doToVo(businResource);
    }

    @Override
    public List<BusinResourceVO> queryList(BusinResourceDTO businResourceDTO) {
        BusinResource businResource = new BusinResource();
        BeanUtils.copyProperties(businResourceDTO, businResource);
        List<BusinResource> businResourceList = listOfBusinResource(businResource, null);
        return doToVos(businResourceList);
    }


    @Override
    public List<BusinResource> listOfBusinResource(BusinResource businResource, List<Long> ids) {
        //查询
        QueryWrapper<BusinResource> queryWrapper = new QueryWrapper<>();
        if (businResource != null) {
            if (businResource.getId() != null) {
                queryWrapper.lambda().eq(BusinResource::getId, businResource.getId());
            }
            if (businResource.getCorrelationType() != null) {
                queryWrapper.lambda().eq(BusinResource::getCorrelationType, businResource.getCorrelationType());
            }
            if (businResource.getCorrelationId() != null) {
                queryWrapper.lambda().eq(BusinResource::getCorrelationId, businResource.getCorrelationId());
            }

            if (businResource.getResourceType() != null) {
                queryWrapper.lambda().eq(BusinResource::getResourceType, businResource.getResourceType());
            }
        }
        if (businResource != null && businResource.getProjectId() != null) {
            queryWrapper.lambda().eq(BusinResource::getProjectId, businResource.getProjectId());
        } else if (ContextUtil.getProjectId() != null) {
            queryWrapper.lambda().eq(BusinResource::getProjectId, ContextUtil.getProjectId());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(BusinResource::getId, ids);
        }
        queryWrapper.lambda().eq(BusinResource::getIsDeleted, BusinessConstant.DELETE_NO);
        List<BusinResource> businResourceList = list(queryWrapper);
        return businResourceList;
    }

    @Override
    public void checkResource(List<Long> ids, Boolean isCheck) {
        List<BusinResource> businResourceList = listOfBusinResource(null, ids);
        if (businResourceList != null && !businResourceList.isEmpty()) {
            for (BusinResource businResource : businResourceList) {
                if (isCheck) {
//                    businResource.setStatus(BusinResourceStatusEnum.NORMAL);
                    businResource.setIsShelves(BusinessConstant.NO);
                } else {
                    businResource.setStatus(BusinResourceStatusEnum.REFUSE);
                }
                updateById(businResource);
            }
        }
    }

    @Override
    public void upResource(List<Long> ids, Integer isShelves) {
        List<BusinResource> businResourceList = listOfBusinResource(null, ids);
        if (businResourceList != null && !businResourceList.isEmpty()) {
            for (BusinResource businResource : businResourceList) {
                businResource.setIsShelves(isShelves);
                updateById(businResource);
            }
        }
    }


    public BusinResourceVO doToVo(BusinResource businResource) {
        if (businResource == null) {
            return null;
        }
        BusinResourceVO businResourceVo = new BusinResourceVO();
        BeanUtils.copyProperties(businResource, businResourceVo);
        businResourceVo.setId(businResource.getId());
        if (businResource.getResourceType() != null && BusinResourceResourceTypeEnum.NEWS.getCode().equals(businResource.getResourceType().getCode())) {
            //新闻
            businResourceVo.setResourceOfNew(JSONObject.parseObject(businResource.getBusinDetails(), ResourceOfNew.class));
        } else if (businResource.getResourceType() != null && BusinResourceResourceTypeEnum.DATA.getCode().equals(businResource.getResourceType().getCode())) {
            //资料
            businResourceVo.setResourceOfFileList(JSONArray.parseArray(businResource.getBusinDetails(), ResourceOfFile.class));
        } else if (businResource.getResourceType() != null && BusinResourceResourceTypeEnum.VIDEO.getCode().equals(businResource.getResourceType().getCode())) {
            //视频
//            businResourceVo.setResourceOfVideoList(JSONArray.parseArray(businResource.getBusinDetails(), ResourceOfVideo.class));
            List<ResourceOfVideo> resourceOfVideoList = JSONArray.parseArray(businResource.getBusinDetails(), ResourceOfVideo.class);
            //视频
            List<String> advertsVideoList = new ArrayList<>();
            List<String> advertsVideoImage = new ArrayList<>();
            if (resourceOfVideoList != null && !resourceOfVideoList.isEmpty()) {
                for (ResourceOfVideo resourceOfVideo : resourceOfVideoList) {
                    advertsVideoImage.add(resourceOfVideo.getHeadImg());
                    advertsVideoList.add(resourceOfVideo.getDataUrl());
                }
                businResourceVo.setVideoText(resourceOfVideoList.get(0).getVideoText());
            }
            businResourceVo.setAdvertsVideo(JSON.toJSONString(advertsVideoList));
            businResourceVo.setAdvertsVideoImage(JSON.toJSONString(advertsVideoImage));
        }
        return businResourceVo;
    }

    public List<BusinResourceVO> doToVos(List<BusinResource> businResourceList) {
        if (businResourceList == null || businResourceList.isEmpty()) {
            return null;
        }
        List<BusinResourceVO> result = new ArrayList<>();
        for (BusinResource businResource : businResourceList) {
            result.add(doToVo(businResource));
        }
        return result;
    }


}
